//
//  ViewController.m
//  LogInViewController
//
//  Created by TuFa on 16/7/9.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "TIANYTXLoginViewController.h"
#import "YTXSecureViewController.h"
#import "TIANYTXRegistrationVC.h"
//#import "AppDelegate.h"

#define imageHeight KScreenWidth*(259.0/640)
#define MainURL  @"http://m.zlifan.com/"
#define KScreenWidth [UIScreen mainScreen].bounds.size.width
#define KScreenHeight [UIScreen mainScreen].bounds.size.height



@interface TIANYTXLoginViewController ()<UITextFieldDelegate,UIScrollViewDelegate>
{
    UIButton *btnLogIn;
    NSTimer *timer;
    NSString *stateString;
    NSArray *arrM;
    UIButton *midBtn;
    UIView *midV;
    UINavigationBar *navBar;
    UIScrollView *scorllV;
    UILabel *envbottomLabel;
}


@end

@implementation TIANYTXLoginViewController

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:YES];
    
    [navBar removeFromSuperview];
    [timer invalidate];
    timer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    stateString = @"0";
    self.title = @"登录";
    
    scorllV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    CGFloat scrollH = KScreenHeight;
    if (KScreenHeight <= 568) {

        scrollH = 600;
    }
    [self.view addSubview:scorllV];
    scorllV.contentSize = CGSizeMake(KScreenWidth, scrollH);
    scorllV.delegate = self;
    
    [self creatSubViews];
}

-(void)creatSubViews{
    
    UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 00, 100, 100)];
    [imgV setImage:[UIImage imageNamed:@"myicon"]];
    [scorllV addSubview:imgV];
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(scorllV.mas_top).offset(15);
        make.centerX.equalTo(scorllV.mas_centerX).offset(0);
        make.width.height.equalTo(@150);
        
    }];
    
    NSArray *arr = @[@"手机号码",@"密码"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [defaults objectForKey:@"ResultAuthData"];
    NSString *loginState= [NSString stringWithFormat:@"%@",dic[@"loginState"]];
    NSString *phone= [NSString stringWithFormat:@"%@",dic[@"phone"]];
    NSString *secure= [NSString stringWithFormat:@"%@",dic[@"secure"]];
    NSString *loginCode = [NSString stringWithFormat:@"%@",dic[@"loginCode"]];
    
    for (int i=0; i<arr.count; i++) {
        
        UITextField *textF = [[UITextField alloc]initWithFrame:CGRectMake(30, imageHeight+20+i*60, KScreenWidth-60, 50)];
        [scorllV addSubview:textF];
        textF.placeholder = arr[i];
        textF.delegate = self;
        textF.tag = 100+i;
        textF.clearButtonMode = UITextFieldViewModeWhileEditing;
        textF.borderStyle = UITextBorderStyleNone;
        textF.layer.borderWidth = 1;
        textF.layer.borderColor = [[UIColor lightGrayColor]CGColor];
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 50)];
        textF.leftView = view;
        textF.leftViewMode = UITextFieldViewModeAlways;
        
        if (i == 0) {
            textF.keyboardType = UIKeyboardTypeNumberPad;
        }
        if ([loginState isEqualToString:@"1"]) {
            if (i == 0) {
                textF.keyboardType = UIKeyboardTypeNumberPad;
//                textF.text = phone;
            }else if(i == 1){
//                textF.text = secure;
            }
        }
        
        
        if(i == 1){
            
//            textF.secureTextEntry = YES;
        }else if(i == 2){
            
//            textF.width = KScreenWidth-180;
//            UIButton *imgBtn = [[UIButton alloc]initWithFrame:CGRectMake(textF.right, textF.origin.y, 120, 50)];
//            [imgBtn addTarget:self action:@selector(imgBtnAction) forControlEvents:UIControlEventTouchUpInside];
//            imgBtn.backgroundColor = [UIColor lightGrayColor];
//            UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 120, 50)];
//            imgV.tag = 230;
//            [imgBtn addSubview:imgV];
//            NSString *urlImg = [NSString stringWithFormat:@"%@api/validateCode",MainURL];
//            [imgV setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlImg]]]];
//            [scorllV addSubview:imgBtn];
//
//            if ([loginCode isEqualToString:@"dc1035Zlifan"]) {
//
//                textF.text = loginCode;
//            }else{
//                textF.text = @"";
//            }
//
//            if ([loginState isEqualToString:@"1"]) {
//
//                [self btnAction]; //记住密码后，自动登录
//            }
        }
    }
    UITextField *textF3 = [scorllV viewWithTag:101];
    btnLogIn = [[UIButton alloc]initWithFrame:CGRectMake(30, textF3.bottom+15, KScreenWidth-60, 44)];
    btnLogIn.backgroundColor = [UIColor lightGrayColor];
    [btnLogIn setTitle:@"登录" forState:UIControlStateNormal];
    btnLogIn.layer.cornerRadius = 7;
    [btnLogIn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
    [scorllV addSubview:btnLogIn];
    
    UIButton *btn12 = [[UIButton alloc]initWithFrame:CGRectMake(32, btnLogIn.bottom+22, 16, 16)];
    btn12.layer.borderWidth = 1;
    btn12.layer.borderColor = [[UIColor grayColor]CGColor];
    btn12.layer.cornerRadius = 2;
    btn12.tag = 750;
    if([loginState isEqualToString:@"1"]){
        btn12.selected = YES;
        btn12.layer.borderWidth = 0;
        stateString = @"1";
    }
    [btn12 addTarget:self action:@selector(btnAction12:) forControlEvents:UIControlEventTouchUpInside];
    [btn12 setBackgroundImage:[UIImage imageNamed:@"dc.png"] forState:UIControlStateSelected];
    btn12.hidden = YES;
    [scorllV addSubview:btn12];
    
    UILabel *label12 = [[UILabel alloc]initWithFrame:CGRectMake(btn12.right+7, btnLogIn.bottom+15, 120, 30)];
    label12.hidden = YES;
    label12.text = @"1周内自动登录";
    label12.textColor = [UIColor grayColor];
    [scorllV addSubview:label12];
    
    
    UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth-120, btnLogIn.bottom+15, 90, 30)];
    [btn2 setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(btnAction2) forControlEvents:UIControlEventTouchUpInside];
    [btn2 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [scorllV addSubview:btn2];
    
    //注册装立方
    UIButton *btn3 = [[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth/2-60, btnLogIn.bottom+60, 120, 40)];
    [btn3 setTitle:@"用户注册" forState:UIControlStateNormal];
    [btn3 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    btn3.titleLabel.font = [UIFont systemFontOfSize:16];
    btn3.layer.borderWidth = 1;
    btn3.layer.borderColor = [[UIColor redColor]CGColor];
    btn3.layer.cornerRadius = 20;
    [btn3 addTarget:self action:@selector(btnAction3) forControlEvents:UIControlEventTouchUpInside];
    [scorllV addSubview:btn3];
    
    
    
//    UILabel *bottomLabel = [[UILabel alloc] init];
//    [bottomLabel bk_whenTapped:^{
//        [LEEAlert actionsheet].config
//                    .LeeTitle(@"选择环境")
//                    .LeeAction(@"DEV环境", ^{
//                        if ([YTXEnvironmentManager environment] == YTXEnvTesting) {
//                            [YTXEnvironmentManager setEnvironment:YTXEnvDevelopment];
//                            [[NSUserDefaults standardUserDefaults] setObject:@(YTXEnvDevelopment) forKey:YTXDebugLocalSaveEnvironment];
//                            [[NSUserDefaults standardUserDefaults] synchronize];
//                            [self setEnv];
//                        }
//                    })
//                    .LeeAction(@"TEST环境", ^{
//                        if ([YTXEnvironmentManager environment] == YTXEnvDevelopment) {
//                            [YTXEnvironmentManager setEnvironment:YTXEnvTesting];
//                            [[NSUserDefaults standardUserDefaults] setObject:@(YTXEnvTesting) forKey:YTXDebugLocalSaveEnvironment];
//                            [[NSUserDefaults standardUserDefaults] synchronize];
//                            [self setEnv];
//                        }
//                    })
//                    .LeeCancelAction(@"取消", ^{
//                    })
//                    .LeeShow();
//    }];
//    bottomLabel.userInteractionEnabled = YES;
//    envbottomLabel = bottomLabel;
//    bottomLabel.textColor = [UIColor blackColor];
//    [self.view addSubview:bottomLabel];
//    [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.equalTo(self.view.mas_bottom).offset(-20);
//        make.centerX.equalTo(self.view.mas_centerX).offset(0);
//        make.height.equalTo(@20);
//    }];
//    [self setEnv];
}

-(void)setEnv{
//    NSString*env =  @"DEV环境";
//    if ([YTXEnvironmentManager environment] ==  YTXEnvTesting) {
//        env = @"TEST环境(点击切换环境)";
//    }
//    if ([YTXEnvironmentManager environment] ==  YTXEnvDevelopment) {
//        env = @"DEV环境(点击切换环境)";
//    }
//    envbottomLabel.text =  env;
}

//获取验证码
-(void)imgBtnAction{
    
    UIImageView *imgV = [scorllV viewWithTag:230];
    NSString *urlImg = [NSString stringWithFormat:@"%@api/validateCode",MainURL];
    [imgV setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlImg]]]];
}

-(void)btnAction12:(UIButton *)btn12{
    
    btn12.selected = !btn12.selected;
    if (btn12.selected) {
        btn12.layer.borderWidth = 0;
        stateString = @"1";
    }else{
        btn12.layer.borderWidth = 1;
        stateString = @"0";
    }
}

-(void)btnAction{
    UITextField *textF1 = [scorllV viewWithTag:100];
    UITextField *textF2 = [scorllV viewWithTag:101];
    UITextField *textF3 = [scorllV viewWithTag:102];
    if (btnLogIn.backgroundColor != [UIColor lightGrayColor]) {
        if (textF1.text.length != 11) {
            [SUIUtils makeShortToastAtCenter:@"手机号码格式有误,请重新填写"];
        }else{
            
            [SVProgressHUD show];
//            NSString *url = [YTXAPIService userLogin];
//
//            NSDictionary *param = @{@"mobile":textF1.text,@"password":textF2.text};
//            [YTXNetWorking postWithUrl:url param:param method:@"POST" success:^(NSDictionary * _Nonnull response) {
//                [SVProgressHUD dismiss];
//                if ([response[@"code"] intValue]==0) {
//                    NSLog(@"loginresponse:%@",response);
//                    [SUIUtils makeShortToastAtCenter:@"登录成功"];
////                    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
////                    appDelegate.loginData = response[@"data"];
////                    NSDictionary *loginData = response[@"data"];
////                    [userDefault setObject:loginData[@"token"] forKey:@"USERTOKEN"];
////                    [userDefault setObject:loginData[@"refreshToken"] forKey:@"USERREFSHTOKEN"];
////                    [userDefault setObject:loginData[@"companyId"] forKey:@"USERCompanyId"];
////                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////                        [appDelegate loadMainTab];
////                     });
//
//                }else{
//                    [SUIUtils makeShortToastAtCenter:response[@"msg"]];
//                }
//            } failure:^(NSError * _Nonnull error) {
//                [SUIUtils makeShortToastAtCenter:error.localizedDescription];
//                [SVProgressHUD dismiss];
//            }];
        }
        NSLog(@"可以登录");
    }else{
        
        NSLog(@"登录NO");
    }
}

-(void)btnAction2{
    
    YTXSecureViewController *secureVC = [[YTXSecureViewController alloc]init];
    [self.navigationController pushViewController:secureVC animated:YES];
    NSLog(@"忘记密码");
}

-(void)btnAction3{
    
    NSLog(@"用户注册");
    TIANYTXRegistrationVC *registeVC = [[TIANYTXRegistrationVC alloc]init];
    [self.navigationController pushViewController:registeVC animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    UITextField *textF1 = [scorllV viewWithTag:100];
    UITextField *textF2 = [scorllV viewWithTag:101];
    UITextField *textF3 = [scorllV viewWithTag:102];
    if (textF1.text.length >= 1 && textF2.text.length >= 1) {
        btnLogIn.backgroundColor = [UIColor colorWithRed:0.002 green:0.774 blue:0.003 alpha:1.000];
    }else{
        btnLogIn.backgroundColor = [UIColor lightGrayColor];
    }
    
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    UITextField *textF1 = [scorllV viewWithTag:100];
    UITextField *textF2 = [scorllV viewWithTag:101];
    if (textF1.text.length >= 1 | textF2.text.length >= 1) {
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(textFTime) userInfo:nil repeats:YES];
    }
    
    UITextField *textF02 = [scorllV viewWithTag:102];
    
    if (textField == textF02) {
        
        //键盘将要出现 发出通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
        
        //键盘将要隐藏
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillHideNotification object:nil];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    UITextField *textF1 = [scorllV viewWithTag:100];
    UITextField *textF2 = [scorllV viewWithTag:101];
    if (textF1.text.length >= 1 && textF2.text.length >= 1) {
        btnLogIn.backgroundColor = [UIColor colorWithRed:0.002 green:0.774 blue:0.003 alpha:1.000];
        //取消定时器
        [timer invalidate];
    }else{
        btnLogIn.backgroundColor = [UIColor lightGrayColor];
    }
    
}

-(void)textFTime{
    
//    NSLog(@"定时器");
    UITextField *textF1 = [scorllV viewWithTag:100];
    UITextField *textF2 = [scorllV viewWithTag:101];
    if (textF1.text.length >= 1 && textF2.text.length >= 1) {
        btnLogIn.backgroundColor = [UIColor colorWithRed:0.002 green:0.774 blue:0.003 alpha:1.000];
        //取消定时器
        [timer invalidate];
    }else{
        btnLogIn.backgroundColor = [UIColor lightGrayColor];
    }
}

//在一个VIewController收起键盘的方法如下:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


#pragma mark - 键盘通知调用方法
-(void)keyBoardShow:(NSNotification *)notif{
    
    //根据通知名获取通知
    if ([notif.name isEqualToString:@"UIKeyboardWillShowNotification"]) {
        
        scorllV.transform = CGAffineTransformMakeTranslation(0, -150);
        
    }else if ([notif.name isEqualToString:@"UIKeyboardWillHideNotification"]){
        
        scorllV.transform = CGAffineTransformMakeTranslation(0, 0);
    }
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
    if (self.isViewLoaded && !self.view.window) {
        
        self.view = nil;
    }
}

/*
 loginresponse:{
     code = 0;
     data =     {
         companyId = 13123213;
         expiration = 1663579246000;
         faceUrl = "https://i.ibb.co/xHWNtPC/image.png";
         name = 15101634697;
         nickname = 15101634697;
         phoneNumber = 15101634697;
         refreshToken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJSRUZSRVNIX1RPS0VOIiwiYXVkIjoiNzQ3MTQxNTY3MTc2NzY5NTM2IiwianNvblRva2VuIjoie1wiYXBwSWRcIjpcIjEwMDAxXCIsXCJjb21wYW55SWRcIjpcIjEzMTIzMjEzXCIsXCJwbGF0Zm9ybUlkXCI6MSxcInVpZFwiOlwiNzQ3MTQxNTY3MTc2NzY5NTM2XCIsXCJ1c2VyTmFtZVwiOlwiMTUxMDE2MzQ2OTdcIn0iLCJpc3MiOiJhdXRoIiwiZXhwIjoxNjYzNTc5MjQ2LCJpYXQiOjE2NTgzOTUyNDZ9.cFHfUKAaJPwqybF3_k1n_K5CpLcdHCnH1cblBW2GN8w";
         token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJBQ0NFU1NfVE9LRU4iLCJhdWQiOiI3NDcxNDE1NjcxNzY3Njk1MzYiLCJqc29uVG9rZW4iOiJ7XCJhcHBJZFwiOlwiMTAwMDFcIixcImNvbXBhbnlJZFwiOlwiMTMxMjMyMTNcIixcInBsYXRmb3JtSWRcIjoxLFwidWlkXCI6XCI3NDcxNDE1NjcxNzY3Njk1MzZcIixcInVzZXJOYW1lXCI6XCIxNTEwMTYzNDY5N1wifSIsImlzcyI6ImF1dGgiLCJleHAiOjE2NjM1NzkyNDYsImlhdCI6MTY1ODM5NTI0Nn0.AEJuvQaSJAK-GBZ14t0QJu_dSK1WtIUT1YSKZxWa6YY";
         uid = 747141567176769536;
     };
     msg = "\U767b\U9646\U6210\U529f";
 }
 */

@end
